package com.kunpu.mami.channel.service;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.kunpu.mami.channel.common.ResultSupport;
import com.kunpu.mami.channel.exception.MamiiException;
import com.kunpu.mami.channel.utils.JacksonUtil;



/**
 * Created with IntelliJ IDEA.
 * User: liuhao
 * 全局异常信息处理类
 */
@Component
public class MamiExceptionHandlerResolver implements HandlerExceptionResolver, Ordered {

    private static final Logger LOG = LoggerFactory.getLogger(MamiExceptionHandlerResolver.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception ex) {
        try {
            writeJsonResponse(ex, response);
        } catch (Exception e) {
            LOG.error("Response JSON Write Output Error : {}", e);
        }
        return null;//返回null表示由下一个ExceptionResolver处理
    }

    private void writeJsonResponse(Exception ex, HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        try {
            MamiiException pex = (MamiiException) ex;
            JacksonUtil.getMapper().writeValue(response.getOutputStream(), new ResultSupport(pex.getErrorCode(), pex.getMessage(),null));
            LOG.error(pex.getMessage());
       } catch (Exception e) {
            String stack = getStackTraceString(ex);
            ResultSupport responseModel = new ResultSupport();
            responseModel.setCode(500);
            responseModel.setMsg("网络有异常!" );
            LOG.error(stack);
            try {
                JacksonUtil.getMapper().writeValue(response.getOutputStream(), responseModel);
            } catch (IOException e1) {
            }
        }
    }

    private String getStackTraceString(Exception e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        try {
            e.printStackTrace(pw);
            return sw.toString();
        } finally {
            pw.close();
        }
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}